export class HTMLActuator {
  tileContainer: any;
  scoreContainer: any;
  timeContainer: any;
  overContainer: any;
  score: number;

  constructor(tileContainer: any, scoreContainer: any, timeContainer: any, overContainer: any) {
    this.tileContainer = tileContainer;
    this.scoreContainer = scoreContainer;
    this.timeContainer = timeContainer;
    this.overContainer = overContainer;
    this.score = 0;
  }
  // 更新页面网格样式和内容
  actuate(grid: { cells: any[]; }, metadata: { score: number; over: boolean; time: number }) {
    const self = this;
    console.log(grid, metadata);

    window.requestAnimationFrame(() => {
      self.clearContainer(self.tileContainer);

      grid.cells.forEach(column => {
        column.forEach((cell: any) => {
          if (cell) {
            self.addTile(cell);
          }
        });
      });

      self.updateScore(metadata.score);
      self.updateTime(metadata.time);
      if (metadata.over) {
        self.updateOver();
      }
    });
  }

  clearContainer(container: { firstChild: any; removeChild: (arg0: any) => void; }) {
    while (container.firstChild) {
      container.removeChild(container.firstChild);
    }
  }
  updateTile
    (tiles: { x: any; y: any; value: any | string | null; isOnBound: boolean, isSelected: boolean }[]) {
    tiles.forEach((tile) => {
      const position = { x: tile.x, y: tile.y };
      const positionClass = this.positionClass(position);
      const dom: any = document.getElementsByClassName(positionClass)?.[0];
      const classes = ["tile", "tile-" + tile.value, positionClass];
      if (tile.isSelected) {
        classes.push('light')
      }
      if (dom) {
        this.applyClasses(dom, classes);
      }
    })
  }

  addTile(tile: { x: any; y: any; value: any | string | null; isOnBound: boolean, isSelected: boolean }) {
    const wrapper = document.createElement("div");
    const position = { x: tile.x, y: tile.y };
    const positionClass = this.positionClass(position);
    // console.log(tile.value);
    const classes = ["tile", "tile-" + tile.value, positionClass];
    if (tile.isSelected) {
      classes.push('light')
    }
    this.applyClasses(wrapper, classes);
    this.tileContainer.appendChild(wrapper);
  }

  applyClasses(element: HTMLDivElement, classes: any[]) {
    element.setAttribute("class", classes.join(" "));
  }

  normalizePosition(position: { x: number; y: number; }) {
    return { x: position.x, y: position.y };
  }

  positionClass(position: { x: any; y: any; }) {
    position = this.normalizePosition(position);
    return "tile-position-" + position.x + "-" + position.y;
  }

  updateScore(score: number) {
    this.clearContainer(this.scoreContainer);

    const difference = score - this.score;
    this.score = score;

    this.scoreContainer.textContent = this.score;

    if (difference > 0) {
      const addition = document.createElement("div");
      addition.classList.add("score-addition");
      addition.textContent = "+" + difference;

      this.scoreContainer.appendChild(addition);
    }
  }

  updateOver() {
    this.overContainer.style.display = "block";
  }

  updateTime(totalMilliseconds: number) {
    // 将总秒数转换为分钟、秒和毫秒
    // const totalMilliseconds = time * 1000; // 转换为毫秒
    const minutes = Math.floor(totalMilliseconds / (1000 * 60));
    const remainingMilliseconds = totalMilliseconds % (1000 * 60);
    const seconds = Math.floor(remainingMilliseconds / 1000);
    const milliseconds = Math.floor((remainingMilliseconds % 1000) / 10); // 取两位毫秒

    // 格式化每个部分，确保显示为两位数
    const formattedMinutes = String(minutes).padStart(2, '0');
    const formattedSeconds = String(seconds).padStart(2, '0');
    const formattedMilliseconds = String(milliseconds).padStart(2, '0');

    this.timeContainer.textContent = `${formattedMinutes}:${formattedSeconds}:${formattedMilliseconds}`;
  }
  drawLine(ways: any[]) {
    console.log('绘制路线', ways);
    const tileSize = 39;
    for (let i = 0; i < ways.length - 1; i++) {
      const p1 = ways[i];
      const p2 = ways[i + 1];
      let abs_x = Math.abs(p1.x - p2.x);//x轴差的绝对值
      let abs_y = Math.abs(p1.y - p2.y);//y轴差的绝对值
      const baseOffset = tileSize / 2;
      let leftOffset = 0;
      let topOffset = 0;
      const line = document.createElement("div")
      // abs_x 判断y轴位置关系，isUp
      if (abs_x == 0) {
        abs_x = 3;//设置成3是为了保证相邻的两个方块之间连线一定的尺寸
        const isUp = p1.y > p2.y; //是否向上绘制
        console.log("isUp", p1, p2, isUp);
        abs_y = abs_y * tileSize
        if (isUp) {
          leftOffset = baseOffset + p1.x * tileSize
          topOffset = baseOffset + p2.y * tileSize
        } else {
          leftOffset = baseOffset + p1.x * tileSize
          topOffset = baseOffset + p1.y * tileSize
        }
        line.classList.add("line_y");

        if (ways.length == 2 && (p1.x == 0 || p1.x == 6)) {
          // ways.length == 2表示只有两个点,在第一列或者最后一列，需要补充两个短线
          const line_min1 = document.createElement("div")
          const line_min2 = document.createElement("div")
          line_min1.classList.add("line_y");
          line_min2.classList.add("line_y");
          const p_offset = tileSize * 0.8
          line_min1.style.width = line_min2.style.width = p_offset + "px"
          line_min1.style.height = line_min2.style.height = 3 + "px"
          if (p1.x == 0) {
            line_min1.style.left = line_min2.style.left = leftOffset - p_offset + "px"
            leftOffset = leftOffset - p_offset
          } else {
            line_min1.style.left = line_min2.style.left = leftOffset + "px"
            leftOffset = leftOffset + p_offset
          }
          line_min1.style.top = topOffset + "px"
          line_min2.style.top = topOffset + abs_y + "px"
          this.tileContainer.appendChild(line_min1);
          this.tileContainer.appendChild(line_min2);
        }
      }

      // abs_y 判断x轴位置关系，isLeft
      if (abs_y == 0) {
        abs_y = 3;
        const isLeft = p1.x > p2.x;//是否向左绘制
        console.log('isLeft', p1, p2, isLeft);
        abs_x = abs_x * tileSize
        if (isLeft) {
          leftOffset = baseOffset + p2.x * tileSize
          topOffset = baseOffset + p1.y * tileSize
        } else {
          leftOffset = baseOffset + p1.x * tileSize
          topOffset = baseOffset + p2.y * tileSize
        }
        line.classList.add("line_x");

        if (ways.length == 2 && (p1.y == 0 || p1.y == 9)) {
          //ways.length == 2表示只有两个点,在第一行或最后一行，补充两个短线
          const line_min1 = document.createElement("div")
          const line_min2 = document.createElement("div")
          line_min1.classList.add("line_x");
          line_min2.classList.add("line_x");
          const p_offset = tileSize * 0.8
          line_min1.style.width = line_min2.style.width = 3 + "px"
          line_min1.style.height = line_min2.style.height = p_offset + "px"
          if (p1.y == 0) {
            line_min1.style.top = line_min2.style.top = topOffset - p_offset + "px"
            topOffset = topOffset - p_offset
          } else {
            line_min1.style.top = line_min2.style.top = topOffset + "px"
            topOffset = topOffset + p_offset
          }
          line_min1.style.left = leftOffset + "px"
          line_min2.style.left = leftOffset + abs_x + "px"
          this.tileContainer.appendChild(line_min1);
          this.tileContainer.appendChild(line_min2);
        }
      }

      line.style.left = leftOffset + "px"
      line.style.top = topOffset + "px"
      line.style.width = abs_x + "px"
      line.style.height = abs_y + "px"
      // console.log(abs_x, abs_y, leftOffset, topOffset);

      this.tileContainer.appendChild(line);
    }
  }
}

